<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\BaseController;
use App\Models\User;
use App\Models\UserBalanceDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PromotionController extends BaseController
{
    public function index()
    {

        $user_id = auth('api')->id();
        $total_income_amount = DB::table('user_balance_details')
                                 ->where('type',4)
                                 ->where('user_id',$user_id)
                                 ->sum('amount');
        $balance = DB::table('users')->where('id',$user_id)->value('balance');


        $child_count = DB::table('users')->where('parent_id',$user_id)->count('id');
        $son_count = DB::select('select count(id) as son_count from users where parent_id in(select id from users where parent_id='.$user_id.')');

        $group_count = $child_count+current($son_count)->son_count;

        $sql1 = '(select sum(amount) from user_balance_details where type=4 and source_income_user_id=users.id) as personal_amount';

        $promotions = DB::table('users')
                        ->selectRaw("id,nickname,$sql1")
                        ->where('parent_id',$user_id)
                        ->simplePaginate();

        foreach ($promotions->items() as $v){

            $v->group_count = DB::table('users')->where('parent_id',$v->id)->count('id');
            $group_amount = DB::select('select sum(amount) as group_amount from user_balance_details where type=4 and user_id='.$user_id.' and source_income_user_id in(select id from users where parent_id='.$v->id.')');
            $v->group_amount = $group_amount[0]->group_amount;
        }

        return $this->success([
            'total_income_amount' => $total_income_amount,
            'balance' => $balance,
            'group_count' => $group_count,
            'promotion' =>  $promotions
        ]);
    }


    public function group(Request $request)
    {
        $param = $this->validate($request,[
            'user_id' => 'required'
        ]);
        $child_count = DB::table('users')
                        ->where('parent_id',$param['user_id'])
                        ->count('id');

        $total_income_amount = DB::table('user_balance_details')
            ->where('type',4)
            ->where('user_id',$param['user_id'])
            ->sum('amount');

        $gorups =  UserBalanceDetail::query()
            ->where('user_id',$param['user_id'])
            ->where('type',4)
            ->with('user:id,avatar,nickname,created_at')
            ->simplePaginate();


        return $this->success([
            'groups' => $gorups,
            'child_count' =>$child_count,
            'total_income_amount' =>$total_income_amount,
        ]);
    }
}
